import socket
import network
import camera
import time
import machine
from machine import Pin
import LED
import Flash
import _thread
import struct

#sta模式，连接到路由器，转发画面
def sta_connect(ssid,pwd):
    LED.led_close(33)
    # 连接wifi前led闪烁快
    LED.led_flash(33,20)
    # 连接wifi
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(ssid, pwd)
        while not wlan.isconnected():
            pass
    print('网络配置:', wlan.ifconfig())
#ap模式，设备发出热点，发送给连接的设备
def ap_connect():
    ap = network.WLAN(network.AP_IF) # create access-point interface
    ap.active(True)         # activate the interface
    ap.config(essid='ESP32cam-AP') # set the SSID of the access point
    ap.config(max_clients=10) # set how many clients can connect to the network
    ap.config(authmode=0)
    
    print('esp热点创建成功')

def init_camera(q):
    # 连接成功后led闪烁慢，配置camera,arg1:33号引脚；arg2:3是频率
    LED.led_flash(33,8)
    # 摄像头初始化
    try:
        camera.init(0, format=camera.JPEG)
    except Exception as e:
        camera.deinit()
        camera.init(0, format=camera.JPEG)
    # 其他设置：
    # 上翻下翻
    camera.flip(1)
    #左/右
    camera.mirror(1)
    # 分辨率
    camera.framesize(camera.FRAME_HVGA)
    # 选项如下：
    # FRAME_96X96 FRAME_QQVGA FRAME_QCIF FRAME_HQVGA FRAME_240X240
    # FRAME_QVGA FRAME_CIF FRAME_HVGA FRAME_VGA FRAME_SVGA
    # FRAME_XGA FRAME_HD FRAME_SXGA FRAME_UXGA FRAME_FHD
    # FRAME_P_HD FRAME_P_3MP FRAME_QXGA FRAME_QHD FRAME_WQXGA
    # FRAME_P_FHD FRAME_QSXGA
    # 有关详细信息，请查看此链接：https://bit.ly/2YOzizz

    # 特效
    camera.speffect(camera.EFFECT_NONE)
    #选项如下：
    # 效果\无（默认）效果\负效果\ BW效果\红色效果\绿色效果\蓝色效果\复古效果
    # EFFECT_NONE (default) EFFECT_NEG \EFFECT_BW\ EFFECT_RED\ EFFECT_GREEN\ EFFECT_BLUE\ EFFECT_RETRO

    # 白平衡
    # camera.whitebalance(camera.WB_HOME)
    #选项如下：
    # WB_NONE (default) WB_SUNNY WB_CLOUDY WB_OFFICE WB_HOME

    # 饱和
    camera.saturation(0)
    #-2,2（默认为0）. -2灰度
    # -2,2 (default 0). -2 grayscale 

    # 亮度
    camera.brightness(0)
    #-2,2（默认为0）. 2亮度
    # -2,2 (default 0). 2 brightness

    # 对比度
    camera.contrast(0)
    #-2,2（默认为0）.2高对比度
    #-2,2 (default 0). 2 highcontrast

    # 质量
    camera.quality(q)
    #10-63数字越小质量越高

def send_data(s):
    # socket UDP 的创建
    LED.led_close(33)
    print('开始发送视频流')
    try:
        while True:
            buf = camera.capture()  # 获取图像数据
            lenth=len(buf)
            if lenth!=0:
                print(lenth)
    #                 防止发过去的文件粘包，需要告诉对方你发的图片长度先
                #由于每次采集图片大小不同，用struct打包
                b_lenth=struct.pack('i',lenth)
                try:
                    s.send(b_lenth)
                    s.send(buf)
                except Exception as e:
                    print(e)
                    print('连接错误，重新连接')
                    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
                    s.connect(('192.168.1.15',9091))
                    print('连接成功')
                    continue
    except Exception as e:
        print('111')
        print(e)
        
    finally:
        camera.deinit()
def receive_data(s):
    print('开始接受信息')
    
    while True:
        data=s.recv(1024)
        print(data)
        # 控制闪光灯
        if data==b'flash':
            Flash.flash()
        # 控制图像质量 quality,传送格式为q#33
        elif b'q' in data:
            data_list=data.split(b'#')
            camera.deinit()
            print(data_list)
            init_camera(q=int(data_list[1]))
    
def main():
    sta_connect('CMCC-PPVi','37jp7j5b')
#     sta_connect('nova','12345678Wyc')
#     ap_connect()
    init_camera(q=60)
    try:
        print('准备连接服务器')
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
        s.connect(('192.168.1.15',9091))
#         s.connect(('43.142.101.253',9091))
        print('连接成功')
        _thread.start_new_thread(receive_data,(s,))
        send_data(s)
    except Exception as e:
        print(e)
    finally:
        camera.deinit()
    
    
main()


